package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"roc/wechat/controller/resp"
	"roc/wechat/global"
	"roc/wechat/services/alarm_msg"
	"roc/wechat/utils"
	"runtime"
	"time"
)

// Recover 异常处理
func Recover() gin.HandlerFunc {
	return func(c *gin.Context) {
		contentType := c.ContentType()
		// 为 multipart forms 设置较低的内存限制（50M） (默认是 32 MiB)
		if contentType == "multipart/form-data" {
			err := c.Request.ParseMultipartForm(10 << 20)
			if err != nil {
				resp.Custom(http.StatusRequestEntityTooLarge, "上传文件太大，err:"+err.Error(), c)
				c.Abort()
				return
			}
		}
		defer func() {
			if err := recover(); err != any(nil) {
				stack := ""

				msg := fmt.Sprintf("The request url is  %v", c.Request.RequestURI)
				stack += msg + "</br>"
				global.LOG.Critical(msg)
				msg = fmt.Sprintf("The request data is %v", c.Params)
				stack += msg + "</br>"
				global.LOG.Critical(msg)
				msg = fmt.Sprintf("Handler crashed with error %v", err)
				stack += msg + "</br>"
				global.LOG.Critical(msg)
				for i := 1; ; i++ {
					_, file, line, ok := runtime.Caller(i)
					if !ok {
						break
					}
					global.LOG.Critical(fmt.Sprintf("%s:%d", file, line))
					stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d</br>", file, line))
				}
				fmt.Println("stack:", stack)
				resp.Custom(http.StatusInternalServerError, "系统异常", c)
				go alarm_msg.SendAlarmMsg(utils.APPNAME+"崩了"+time.Now().Format("2006-01-02 15:04:05")+";Err:"+stack, 3)
				return
			}
		}()
		c.Next()
	}
}
